<template>
    <div class="main">
        <div class="search">
            <label>用户组搜索：</label>
            <el-input v-model="ad.name" style="width: 240px" placeholder="请输入姓名" clearable>
            </el-input>
            <el-button type="primary" @click="search" style="margin-left: 10px;">查询</el-button>
            <el-button type="primary" style="margin-left: 10px;" @click="resetSearch">重置</el-button>
            <el-button class="button" :icon="Plus" @click="add">添加</el-button>
            <el-button class="button" :icon="Delete" @click="deleteRows">批量删除</el-button>
        </div>
        <div class="data">
            <div class="gird">
                <el-table :data="tableData" border style="width: 100%" :header-cell-style="{ textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }" ref="tableRef">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="id" label="编号" width="80" />
                    <el-table-column prop="name" label="姓名" width="140" />
                    <el-table-column prop="description" label="描述" width="140" />
                    <el-table-column prop="enabled" label="是否启用" width="120">
                        <template #default="scope">
                            <el-switch @change="updateEnabled123(scope.row)" v-model="scope.row.enabled" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdTime" label="创建时间" width="240" />
                    <el-table-column prop="updatedTime" label="上次更新" width="240" />
                    <el-table-column prop="createdBy" label="创建者" width="240" />
                    <el-table-column prop="createdBy" label="修改者" width="240" />
                    <el-table-column fixed="right" label="操作" min-width="200">
                        <template #default="scope">
                            <el-button type="primary" :icon="Edit" @click="editRow(scope.row)"
                                size="small">编辑</el-button>
                            <el-button type="danger" :icon="Delete" @click="deleteRow(scope.row)" size="small">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="pagination" style="margin-top: 10px;">
                <el-pagination v-model:current-page="pi.pageNo" v-model:page-size="pi.pageSize"
                    :page-sizes="[5, 10, 15, 30, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pi.total" background @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-dialog v-model="show" :title="title" width="500" draggable :close-on-click-modal="false">
            <!-- 新增操作的表单 -->
            <el-form :model="afm" ref="sfRef" label-width="100px">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="用户组名称" prop="name">
                            <el-input v-model="afm.name" placeholder="请输入用户组名称"></el-input>
                        </el-form-item>
                        <el-form-item label="是否启用" prop="enabled">
                            <el-select v-model="afm.enabled" placeholder="请选择是否启用" style="width: 100%">
                                <el-option label="启用" :value="true" />
                                <el-option label="禁用" :value="false" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="用户组描述" prop="description">
                            <el-input 
                                v-model="afm.description" 
                                type="textarea"
                                :rows="3"
                                placeholder="请输入用户组描述"
                                style="width: 100%">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="show = false">取消</el-button>
                    <el-button type="primary" @click="submitForm"> 确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { Plus, Edit, Search, Refresh, Delete, CircleClose, CircleCheck } from '@element-plus/icons-vue'
import { ref, onMounted, toRaw, nextTick } from 'vue';
import {
  findAll,
  deleteById,
  save,
  updateAdmin,
  updateEnabled as updateUserEnabled,
  findById,
  updateRole as updateRoleAdmin,
  deleteAll,
  findUserGroup,
  saveUserGroup,
  updateUserGroup,
  deleteUserGroupById,
  deleteAllUserGroup
} from "@/api/AdminApi"
import { ElMessageBox, ElMessage } from 'element-plus'
onMounted(() => {
    search();
})

const tableData = ref();
async function search() {
    let params = ad.value;
    let resp = await findUserGroup(pi.value.pageNo, pi.value.pageSize, params);
    // console.log("分页"+pi.value.pageNo, pi.value.pageSize)
    if (resp.records) {
        tableData.value = resp.records;
    }
    // console.log(resp.data)
    pi.value.pageNo = resp.current || pi.value.pageNo;
    pi.value.total = resp.total || 0;
    pi.value.pageSize = resp.size || pi.value.pageSize;
    if (tableData.value) {
        tableData.value = tableData.value.map(item => {
            // 将 status 字段从 0/1 转换为 false/true
            return {
                ...item,
                enabled: item.enabled === true,
            };
        });
    }
    console.log("分页详细"+pi.value.total)
}

//分页信息
const pi = ref({
    pageNo: 1,
    pageSize: 5,
    total: 0,
});

//分页查询
function handleSizeChange(val) {
    pi.value.pageSize = val;
    pi.value.pageNo = 1;
    search();
}

function handleCurrentChange(val) {
    pi.value.pageNo = val;
    search();
}

const ad = ref({
    name: "",
});
function resetSearch() {
    ad.value = {
        name: "",
    };
    search();
}
//点击行数后单选框被勾选
let tableRef;
//批量删除
function deleteRows() {
    let rows = tableRef.getSelectionRows();
    let ids = [];
    for (let row of rows) {
        ids.push(toRaw(row).id);
    }
    deleteAllRows(ids);
}
async function deleteAllRows(ids) {
    if (ids.length == 0) {
        ElMessage({
            message: "请选择想要删除的行",
            type: "warning",
        });
    } else {
        ElMessageBox.confirm("是否确认删除所选行?", "Warning", {
            type: "warning",
        })
            .then(async () => {
                //向后台发送ajax请求
                let resp = await deleteAllUserGroup(ids);
                if (resp.code == 200) {
                    ElMessage({
                        message: resp.msg,
                        type: "success",
                    });
                    search();
                } else {
                    ElMessage({
                        message: resp.msg,
                        type: "warning",
                    });
                }
            })
            .catch(() => { });
    }
}
async function updateEnabled123(row) {
    // console.log(admin);
    if (row.enabled === false) {
        let resp = await updateUserEnabled(row.id, false);
        if (resp.code == '200') {
            ElMessage({
                message: "禁用成功",
                type: "success",
            });
        }
        else {
            ElMessage({
                message: resp.msg,
                type: "error",
            });
        }
    }
    else {
        let resp = await updateUserEnabled(row.id, true);
        if (resp.code == '200') {
            ElMessage({
                message: "启用成功",
                type: "success",
            });
        }
        else {
            ElMessage({
                message: resp.msg,
                type: "error",
            });
        }
    }
}
async function updateRole(row) {
    console.log(row.role);
    // console.log(row.id);
    await updateRoleAdmin(row.id, row.role);
    ElMessage({
        message: "权限修改成功",
        type: "success",
    });
}

function deleteRow(row) {
    let id = row.id;
    deleteAdmin(id)
}

//删除函数
function deleteAdmin(id) {
    ElMessageBox.confirm("是否确认删除所选行?", "警告！", {
        type: "warning",
    })
        .then(async () => {
            let resp = await deleteUserGroupById(id);
            if (resp.code == '200') {
                console.log("111")
                ElMessage({
                    message: resp.msg,
                    type: "success",
                });
                search();
            } else {
                ElMessage({
                    message: resp.msg,
                    type: "error",
                });
            }
        })
        .catch(() => { });
}
const show = ref(false);

const afm = ref({
  id: "",
  name: "",
  description: "",
  enabled: "",
  role: "",
})
const title = ref("新增用户组");
function add() {
    show.value = true;
    title.value = "新增用户组";
    afm.value = { // 重置表单数据
        id: "",
        name: "",
        description: "",
        enabled: "",
        role: "",
    };
}
function submitForm() {
    let adm = toRaw(afm.value);
    // console.log(adm);
    if (adm.id) {
        update(adm);
    } else {
        saveUser(adm);
    }
}
async function saveUser(adm) {
    let resp = await saveUserGroup(adm);
    console.log(resp.data);
    if (resp.code == 200) {
        ElMessage({
            message: resp.msg,
            type: "success",
        });
        search();
        show.value = false;
    } else {
        ElMessage({
            message: resp.msg,
            type: "error",
        });
    }
}

function editRow(row) {
    row = Object.assign({}, row);
    show.value = true;
    title.value = "修改管理员";
    if (row.status == false) {
        row.status = 0;
    } else {
        row.status = 1;
    }
    nextTick(() => {
        afm.value = row;
    });
}

async function update(adm) {
    let resp = await updateUserGroup(adm);
    if (resp.code == 200) {
        ElMessage({
            message: resp.msg,
            type: 'success',
        });
        await search();
        show.value = false;
    } else {
        ElMessage({
            message: resp.msg,
            type: 'error',
        });
    }
}

</script>

<style scoped>
.main {
    padding: 0 20px;
}

.data>.pagination {
    margin-top: 10px;
    float: right;
}

.data {
    margin-top: 20px;
}

.search {
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 20px;
    border: 1px solid #ebeef5;
    margin-top: 20px;
}

.mid {
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 20px;
    border: 1px solid #ebeef5;
    margin-top: 20px;
    height: 50px;
}

.search>.button {
    float: right;
}

.el-table td.is-center,
.el-table th.is-center {
    text-align: center;
}

.avatar {
    width: 80px;
    height: 80px;
    border: 1px dashed #ccc;
    border-radius: 4px;
    margin-left: 8px;
    display: flex;
}

.avatar {
    width: 80px;
    height: 80px;
    border: 1px dashed #ccc;
    border-radius: 4px;
    margin-left: 8px;
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
}


.avatar .img {
    width: 80px;
    height: 80px;
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center center;
}
</style>
